class Comment < ActiveRecord::Base
	apply_simple_captcha
	validates_presence_of :comment
	
  belongs_to :commentable, :polymorphic => true, :counter_cache=>:comments_count
  belongs_to :user
  belongs_to :avatar
  has_many :children, :class_name => 'Comment', :foreign_key => 'parent_id', :dependent => :nullify 
 
  attr_writer :subcomments
  attr_accessor :root

	acts_as_threaded
	
	named_scope :visible, :conditions=>{:is_visible=>true}
	named_scope :roots, :conditions=>{:parent_id=>nil}
	
	auto_html_for :comment do
		image
		link :target => "_blank", :rel => "nofollow"
		
		# <com value="techno" /> - комьюнити
		# <user value="test_1"/> - пользователь
		# <inside value="название подкаченного">информация которая подкачена</inside>
		prodject_format
  end

	def anonymous?
		self.user_id.zero?
	end
	
	def user_avatar
		return if anonymous?
		return user.avatar if self.avatar.nil?
		user.avatars.find_by_id(self.avatar_id)
	end

  def subcomments
    @subcomments ||= []
  end 
 
  def self.find_comments_by_user(user)
    find(:all,
      :conditions => ["user_id = ?", user.id],
      :order => "created_at DESC")
  end
  
  def self.find_comments_for_commentable(commentable_str, commentable_id)
    find(:all,
      :conditions => ["commentable_type = ? and commentable_id = ?", commentable_str, commentable_id],
      :order => "created_at DESC"
    )
  end

  def self.find_commentable(commentable_str, commentable_id)
    commentable_str.constantize.find(commentable_id)
  end
  
  def object
  	@object ||= Object.const_get(self.commentable_type).find(self.commentable_id)
  	@object
  end
end
